<template>
  <div class="app-container">
    <el-row>
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :inline="true" v-show="showSearch" label-width="auto" :label-position="isPhone ? 'top' : 'left'">
          <el-form-item label="姓名">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="学校">
            <el-select
              v-model="queryParams.trainUniversity"
              placeholder="请选择学校"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in university"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专业">
            <el-input
              v-model="queryParams.trainMajor"
              placeholder="请输入专业"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="培养单位">
            <el-input
              v-model="queryParams.aa1"
              placeholder="请输入培养单位"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="入企时间">
            <el-input
              v-model="queryParams.aa2"
              placeholder="请输入入企时间"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="完成入企手续办理">
            <el-select
              v-model="queryParams.completeJoinProcedure"
              placeholder="请选择"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="完成三方协议签订">
            <el-select
              v-model="queryParams.completeSignAgreement"
              placeholder="请选择"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="完成入企培训导入">
            <el-select
              v-model="queryParams.completeInductionTrain"
              placeholder="请选择"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="完成办公资源配备">
            <el-select
              v-model="queryParams.completeAllocationResources"
              placeholder="请选择"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="完成党员档案转档">
            <el-select
              v-model="queryParams.completeTransferParty"
              placeholder="请选择"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否入住公寓">
            <el-select
              v-model="queryParams.stayApartment"
              placeholder="请选择"
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasRole="[
                'admin',
                'enterprise_depart_admin',
                'enterprise_unit_admin',
              ]"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="姓名"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            width="100"
          />
          <el-table-column
            label="学校"
            align="center"
            key="trainUniversity"
            prop="trainUniversity"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            width="150"
          >
            <template #default="scope">
              {{ getUniversityText(scope.row.trainUniversity) }}
            </template>
          </el-table-column>
          <el-table-column
            label="专业"
            align="center"
            key="trainMajor"
            prop="trainMajor"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="培养单位"
            align="center"
            key="aa1"
            prop="aa1"
            v-if="columns[4].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="入企时间"
            align="center"
            key="aa2"
            prop="aa2"
            v-if="columns[5].visible"
            :show-overflow-tooltip="true"
            width="150"
          />
          <el-table-column
            label="完成入企手续办理"
            align="center"
            key="completeJoinProcedure"
            prop="completeJoinProcedure"
            v-if="columns[6].visible"
            width="140"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.completeJoinProcedure === 'Y' ? 'success' : 'info'
                "
              >
                {{
                  scope.row.completeJoinProcedure === "Y" ? "已完成" : "未完成"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="完成三方协议签订"
            align="center"
            key="completeSignAgreement"
            prop="completeSignAgreement"
            v-if="columns[7].visible"
            width="140"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.completeSignAgreement === 'Y' ? 'success' : 'info'
                "
              >
                {{
                  scope.row.completeSignAgreement === "Y" ? "已完成" : "未完成"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="上传三方协议附件（签字盖章版）"
            align="center"
            key="fileObjects"
            prop="fileObjects"
            v-if="columns[8].visible"
            width="200"
          >
            <template #default="scope">
              <div v-if="scope.row.fileObjects">
                <div
                  v-for="(item, i) in scope.row.fileObjects"
                  :key="i"
                  @click="downloadFile(item)"
                  style="color: #409EFF;cursor: pointer;"
                >
                  {{ item.fileName }}
                </div>
              </div>
              <div v-else>暂无</div>
            </template>
          </el-table-column>
          <el-table-column
            label="完成入企培训导入"
            align="center"
            key="completeInductionTrain"
            prop="completeInductionTrain"
            v-if="columns[9].visible"
            width="140"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.completeInductionTrain === 'Y' ? 'success' : 'info'
                "
              >
                {{
                  scope.row.completeInductionTrain === "Y" ? "已完成" : "未完成"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="完成办公资源配备"
            align="center"
            key="completeAllocationResources"
            prop="completeAllocationResources"
            v-if="columns[10].visible"
            width="140"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.completeAllocationResources === 'Y'
                    ? 'success'
                    : 'info'
                "
              >
                {{
                  scope.row.completeAllocationResources === "Y"
                    ? "已完成"
                    : "未完成"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="完成党员档案转档"
            align="center"
            key="completeTransferParty"
            prop="completeTransferParty"
            v-if="columns[11].visible"
            width="140"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.completeTransferParty === 'Y' ? 'success' : 'info'
                "
              >
                {{
                  scope.row.completeTransferParty === "Y" ? "已完成" : "未完成"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="是否入住公寓"
            align="center"
            key="stayApartment"
            prop="stayApartment"
            v-if="columns[12].visible"
            width="120"
          >
            <template #default="scope">
              <el-tag
                :type="scope.row.stayApartment === 'Y' ? 'success' : 'info'"
              >
                {{ scope.row.stayApartment === "Y" ? "是" : "否" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="详情" placement="top">
                <el-button
                  link
                  type="info"
                  icon="View"
                  @click="handleDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasRole="[
                    'admin',
                    'enterprise_depart_admin',
                    'enterprise_unit_admin',
                  ]"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasRole="['admin', 'enterprise_unit_admin']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="提交"
                placement="top"
                v-if="
                  scope.row.approvalStatus === 'no_submit' ||
                  scope.row.approvalStatus === 'rejected'
                "
              >
                <el-button
                  link
                  type="warning"
                  icon="Upload"
                  @click="handleSubmit(scope.row)"
                  v-hasRole="[
                    'admin',
                    'enterprise_depart_admin',
                    'enterprise_unit_admin',
                  ]"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                content="审批"
                placement="top"
                v-if="scope.row.approvalAuth"
              >
                <el-button
                  link
                  type="success"
                  icon="Check"
                  @click="handleApprove(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" :label-position="isPhone ? 'top' : 'left'">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="学生" prop="userId" label-width="50px">
              <el-select
                v-model="form.userId"
                placeholder="请选择学生"
                clearable
                :disabled="title === '查看入企实践信息详情'"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="formUserInfo">
            <el-col :span="12">
              <el-form-item label="学校" label-width="50px">
                <el-input :value="getUniversityText(formUserInfo.trainUniversity)" disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" label-width="50px">
                <el-input v-model="formUserInfo.trainMajor" disabled>
                </el-input>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="12">
            <el-form-item label="完成入企手续办理" prop="completeJoinProcedure">
              <el-radio-group v-model="form.completeJoinProcedure" :disabled="title === '查看入企实践信息详情'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成三方协议签订" prop="completeSignAgreement">
              <el-radio-group v-model="form.completeSignAgreement" :disabled="title === '查看入企实践信息详情'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.completeSignAgreement === 'Y'">
            <el-form-item label="上传三方协议附件" prop="fileObjects">
              <file-upload
                v-model="form.fileObjects"
                ref="fileUploadRef"
                :limit="10"
                :fileSize="100"
                :disabled="title === '查看入企实践信息详情'"
                :fileType="[
                  'pdf',
                  'doc',
                  'docx',
                  'xls',
                  'xlsx',
                  'ppt',
                  'pptx',
                  'zip',
                  '7z',
                  'rar',
                  'jpg',
                  'jpeg',
                  'png',
                ]"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="完成入企培训导入"
              prop="completeInductionTrain"
            >
              <el-radio-group v-model="form.completeInductionTrain" :disabled="title === '查看入企实践信息详情'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="完成办公资源配备"
              prop="completeAllocationResources"
            >
              <el-radio-group v-model="form.completeAllocationResources" :disabled="title === '查看入企实践信息详情'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成党员档案转档" prop="completeTransferParty">
              <el-radio-group v-model="form.completeTransferParty" :disabled="title === '查看入企实践信息详情'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否入住公寓" prop="stayApartment">
              <el-radio-group v-model="form.stayApartment" :disabled="title === '查看入企实践信息详情'">
                <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form-item
        label="审核意见"
        prop="approvalRemark"
        style="margin-bottom: 0"
        v-if="form.approvalStatus === 'rejected'"
      >
        <el-input
          v-model="form.approvalRemark"
          disabled
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <!-- 审批模式下的审核意见字段 -->
          <div v-if="title === '审批入企实践信息'" style="margin-bottom: 20px">
            <el-form-item
              label="审核意见"
              prop="approvalRemark"
              style="margin-bottom: 0"
            >
              <el-input
                v-model="form.approvalRemark"
                type="textarea"
                placeholder="请输入审核意见"
                :rows="3"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </div>

          <!-- 普通编辑模式按钮 -->
          <template v-if="title !== '审批入企实践信息' && title !== '查看入企实践信息详情'">
            <el-button 
              type="primary" 
              @click="submitForm"
              :loading="submitLoading"
              :disabled="submitLoading"
            >确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>

          <!-- 详情模式按钮 -->
          <template v-if="title === '查看入企实践信息详情'">
            <el-button @click="cancel">关 闭</el-button>
          </template>

          <!-- 审批模式按钮 -->
          <template v-else>
            <el-button 
              type="success" 
              @click="handleApprovePass"
              :loading="approvePassLoading"
              :disabled="approvePassLoading"
              >通 过</el-button
            >
            <el-button 
              type="danger" 
              @click="handleApproveReject"
              :loading="approveRejectLoading"
              :disabled="approveRejectLoading"
              >驳 回</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EnterprisePracticeManage">
import {
  getList,
  addItem,
  editItem,
  delItem,
  getDetail,
} from "@/api/enterprise-practice-manage";
import { submitApproval, handleApproval } from "@/api/approval";
import { getStudentList } from "@/api/common";
import { saveAs } from "file-saver";
import FileUpload from "@/components/FileUpload";
import { v4 as uuidv4 } from "uuid";
import { isPhone } from "@/utils/index";

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_yes_no, university } = proxy.useDict("sys_yes_no", "university");

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const fileUploadRef = ref(null);

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `学校`, visible: true },
  { key: 3, label: `专业`, visible: true },
  { key: 4, label: `培养单位`, visible: true },
  { key: 5, label: `入企时间`, visible: true },
  { key: 6, label: `完成入企手续办理`, visible: true },
  { key: 7, label: `完成三方协议签订`, visible: true },
  { key: 8, label: `上传三方协议附件（签字盖章版）`, visible: true },
  { key: 9, label: `完成入企培训导入`, visible: true },
  { key: 10, label: `完成办公资源配备`, visible: true },
  { key: 11, label: `完成党员档案转档`, visible: true },
  { key: 12, label: `是否入住公寓`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: undefined,
    trainUniversity: undefined,
    trainMajor: undefined,
    aa1: undefined,
    aa2: undefined,
    completeJoinProcedure: undefined,
    completeSignAgreement: undefined,
    completeInductionTrain: undefined,
    completeAllocationResources: undefined,
    completeTransferParty: undefined,
    stayApartment: undefined,
  },
  rules: {
    userId: [{ required: true, message: "请选择学生", trigger: "change" }],
    completeJoinProcedure: [
      { required: true, message: "请选择完成入企手续办理", trigger: "change" },
    ],
    completeSignAgreement: [
      { required: true, message: "请选择完成三方协议签订", trigger: "change" },
    ],
    fileObjects: [
      { required: true, message: "请上传三方协议附件", trigger: "change" },
    ],
    completeInductionTrain: [
      { required: true, message: "请选择完成入企培训导入", trigger: "change" },
    ],
    completeAllocationResources: [
      { required: true, message: "请选择完成办公资源配备", trigger: "change" },
    ],
    completeTransferParty: [
      { required: true, message: "请选择完成党员档案转档", trigger: "change" },
    ],
    stayApartment: [
      { required: true, message: "请选择是否入住公寓", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const userList = ref([]);

// 按钮loading状态
const submitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);

const formUserInfo = computed(() =>
  userList.value.find((t) => t.userId === form.value.userId)
);

/** 查询用户列表 */
function handleGetList() {
  loading.value = true;
  getList(queryParams.value).then((res) => {
    loading.value = false;
    list.value = res.rows;
    total.value = res.total;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    nickName: undefined,
    trainUniversity: undefined,
    trainMajor: undefined,
    aa1: undefined,
    aa2: undefined,
    completeJoinProcedure: undefined,
    completeSignAgreement: undefined,
    completeInductionTrain: undefined,
    completeAllocationResources: undefined,
    completeTransferParty: undefined,
    stayApartment: undefined,
  };
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + id + '"的数据项？')
    .then(function () {
      return delItem(id);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    completeJoinProcedure: "N",
    completeSignAgreement: "N",
    completeInductionTrain: "N",
    completeAllocationResources: "N",
    completeTransferParty: "N",
    stayApartment: "N",
    fileObjects: [],
  };
  proxy.resetForm("formRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加入企实践信息";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = response.data;

    if (form.value.fileObjects) {
      form.value.fileObjects = form.value.fileObjects.map((t) => ({
        id: uuidv4(),
        name: t.fileName,
        url: t.filePath,
      }));
    }

    open.value = true;
    title.value = "修改入企实践信息";
  });
}
/** 提交按钮 */
function submitForm() {
  // 防止重复提交
  if (submitLoading.value) return;
  
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      
      // 整理文件数据 - FileUpload 组件返回的是字符串，需要转换为对象数组
      const fileObjects = fileUploadRef.value.fileList
        ? fileUploadRef.value.fileList.map((t) => ({
            fileName: t.name.split("/").pop(),
            filePath: t.url,
          }))
        : [];

      const submitData = {
        ...form.value,
        fileObjects,
      };

      if (form.value.id != undefined) {
        editItem(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          handleGetList();
        }).catch((error) => {
          console.error("修改失败:", error);
        }).finally(() => {
          submitLoading.value = false;
        });
      } else {
        addItem(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          handleGetList();
        }).catch((error) => {
          console.error("新增失败:", error);
        }).finally(() => {
          submitLoading.value = false;
        });
      }
    }
  });
}

// 提交审核
function handleSubmit(row) {
  const id = row.id || ids.value;
  const item = list.value.find(item => item.id === id);
  proxy.$modal
    .confirm("是否确认提交审核？")
    .then(function () {
      return submitApproval({
        businessId: id,
        approvalTypeCode: "ent_join_manage_flow",
        approvalInfo: JSON.stringify(item)
      });
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("提交成功");
    })
    .catch(() => {});
}

// 审批操作
function handleApprove(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = {
      ...response.data,
      approvalRemark: "",
    };
    open.value = true;
    title.value = "审批入企实践信息";
  });
}

// 通过审批
function handleApprovePass() {
  // 防止重复提交
  if (approvePassLoading.value) return;
  
  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "approved",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("审批通过");
    open.value = false;
    handleGetList();
  }).catch((error) => {
    console.error("审批通过失败:", error);
  }).finally(() => {
    approvePassLoading.value = false;
  });
}

// 驳回审批
function handleApproveReject() {
  if (!form.value.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  // 防止重复提交
  if (approveRejectLoading.value) return;
  
  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData).then(() => {
    proxy.$modal.msgSuccess("已驳回");
    open.value = false;
    handleGetList();
  }).catch((error) => {
    console.error("审批驳回失败:", error);
  }).finally(() => {
    approveRejectLoading.value = false;
  });
}

function downloadFile(item) {
  saveAs(import.meta.env.VITE_APP_BASE_API + item.filePath, item.fileName);
}

// 高校名称文本显示函数
const getUniversityText = (universityValue) => {
  if (!universityValue) return "未知";
  const dict = university.value?.find((item) => item.value === universityValue);
  return dict ? dict.label : universityValue;
};

// 详情操作
function handleDetail(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id).then((response) => {
    form.value = response.data;

    if (form.value.fileObjects) {
      form.value.fileObjects = form.value.fileObjects.map((t) => ({
        id: uuidv4(),
        name: t.fileName,
        url: t.filePath,
      }));
    }

    open.value = true;
    title.value = "查看入企实践信息详情";
  });
}

handleGetList();
getStudentList({ roleKey: "student" }).then((res) => {
  userList.value = res.data;
});
</script>
